package com.topone.controller;


import com.topone.Exception.FanZoneException;
import com.topone.Utils.ResultVOUntil;
import com.topone.VO.ResultVO;
import com.topone.dto.TcUserCouponDTO;
import com.topone.service.TcUserCouponService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/bussinessCheckCoupon")
@Slf4j
@CrossOrigin
public class BussinessCheckCouponController {

    @Autowired
    private TcUserCouponService userCouponService;


    @PostMapping("/list")
    public ResultVO<Map<String, Object>> list(@RequestParam(value = "userPhone", required = false) String userPhone,
                                              @RequestParam(value = "couponCode", required = false) String userCouponCode,
                                              Map<String, Object> map) {
        if (!StringUtils.isEmpty(userPhone) || !StringUtils.isEmpty(userCouponCode)) {
            try {
                List<TcUserCouponDTO> userCouponDTOList = userCouponService.findUserCouponList(userPhone, userCouponCode);
                map.put("userCouponDTOList", userCouponDTOList);
            } catch (FanZoneException e) {
                log.error("【 商家查询核销用户优惠券】失败", e);
                map.put("error", e.getMessage());
                return ResultVOUntil.error(1, e.getMessage());
            }
        } else {
            log.info("【 商家查询核销用户优惠券】参数不能都为空");
            map.put("error", "用户手机号和优惠券code不能为空");
        }
        log.debug("【商家查询核销用户优惠券】:{}",map);
        return ResultVOUntil.success(map);
    }

    @GetMapping("/check")
    public ResultVO<Map<String, Object>> checkCoupon(@RequestParam("couponId") String userCouponId,
                                                     Map<String, Object> map) {
        try {
            String result = userCouponService.updateUserCouponById(userCouponId);
            map.put("result", result);
            if ("error".equals(result)) {
                log.info("查询不到优惠券");
                return ResultVOUntil.error(1,"查询不到优惠券");
            } else {
                log.info("使用成功,userCouponId={}", userCouponId);
                return ResultVOUntil.success(map);
            }
        } catch (FanZoneException e) {
            log.error("【 商家核销用户优惠券】失败", e);
            map.put("error",e.fillInStackTrace());
            return ResultVOUntil.error(1, e.getMessage());
        }
    }
}
